#! /usr/bin/perl -w
use strict;
use warnings;



sub numpre_main{
	#phase 1
	my $p_map = mapping();
	$p_map = read_question( $p_map );
	$p_map = all_check( $p_map );

}

sub all_check{
	my ( $p_map ) = @_;
	my $flag = 1;
	foreach my $x ( 1..9 ){
		foreach my $y ( 1..9 ){
			if( $p_map->[ $x ]->[ $y ]->[ 0 ] != 0 ){
				$flag = 0;
				last;
			}
		}
	}
	print_map( $p_map ) if( $flag );
	return $p_map;
}

sub print_map{
	my( $p_map ) = @_;
	my $string = '';
	my $yoko = '+' . '---+' x 9;
	foreach my $y ( 1..9 ){
		print "$yoko\n";
		$string = '|';
		foreach my $x ( 1..9 ){
			$string .= ' '. $p_map->[ $x ]->[ $y ]->[ 0 ] . ' |';
		}
		print "$string\n";
	}
	print "$yoko\n\n\n";
	exit;
}


sub read_question{
	my ( $p_map ) = @_;
	my $line;
	my $p_field;
	my $x = 0;
	my $y = 0;
	if( !-e './q.txt' ){
		print "q.txt is not exists.";
		exit;
	}
	open( RP, "<./q.txt");
	while( $line = <RP> ){
		$y++;
		@$p_field = split( /\t/, $line, -1 );
		foreach my $value ( @$p_field ){
			$x = 0;
			if( $value ne '' && $value ne '0' ){
				$x++;
				$p_map = decision   ( $p_map, $x, $y, $value );
				$p_map = kill_number( $p_map, $x, $y, $value );
			}
		}
	}
	close( RP );
}

sub check_number{
	my ( $p_map, $x, $y ) = @_;
	my $value;
	my $count = 0;
	return $p_map if( $p_map->[ $x ]->[ $y ]->[ 0 ] != 0 );
	foreach my $z ( 1..9 ){
		$count += $p_map->[ $x ]->[ $y ]->[ $z ];
		$value = $z;
	}
	if( $count == 1 ){
		$p_map = decision   ( $p_map, $x, $y, $value );
		$p_map = kill_number( $p_map, $x, $y, $value );
	}
}

sub kill_number{
	my ( $p_map, $x, $y, $z ) = @_;
	my $x_joyo = ( $x - 1 ) % 3;
	my $y_joyo = ( $y - 1 ) % 3;
	foreach my $i ( 1..9 ){
		next if( $x == $i );
		$p_map->[ $i ]->[ $y ]->[ $z ] = 0;
		$p_map = check_number( $p_map, $i, $y );
	}
	foreach my $i ( 1..9 ){
		next if( $y = $i );
		$p_map->[ $x ]->[ $i ]->[ $z ] = 0;
		$p_map = check_number( $p_map, $x, $i );
	}
	foreach my $ix ( $x - $x_joyo .. $x - $x_joyo + 2 ){
		foreach my $iy ( $y - $y_joyo .. $y - $y_joyo + 2 ){
			next if(   $ix == $x && $iy == $y );
			$p_map->[ $ix ]->[ $iy ]->[ $z ] = 0;
			$p_map = check_number( $p_map, $ix, $iy );
		}
	}
	return $p_map;
}

sub decision{
	my ( $p_map, $x, $y, $value ) = @_;
	return $p_map if( $p_map->[ $x ]->[ $y ]->[ 0 ] != 0 );
	$p_map->[ $x ]->[ $y ]->[ 0 ] = $value;
	foreach my $z ( 1..9 ){
		next if( $z == $value );
		$p_map->[ $x ]->[ $y ]->[ $z ] = 0;
	}
	return $p_map;
}

sub mapping{
	my $p_map;
	foreach my $x ( 1..9){
		foreach my $y ( 1..9 ){
			foreach my $z ( 1..9 ){
				$p_map->[ $x ]->[ $y ]->[ $z ] = 1;
			}
			$p_map->[ $x ]->[ $y ]->[ 0 ] = 0;
		}
	}
	return $p_map;
}


1;